package com.ctz.commonframe.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Display;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

import java.util.ArrayList;
import java.util.List;

public class PermissonUtil {
    private static final int REQUEST_CODE_PERMISSIONS = 9000;//权限请求码
    private static PermissonUtil instance;
    private OnPermissionResultListener onPermissionResultListener;
    private boolean showSettingsWhenDenied = true;
    private AlertDialog mPermissionDialog;

    private PermissonUtil () {}

    public static synchronized PermissonUtil getInstance() {
        if (instance == null) {
            instance = new PermissonUtil();
        }
        return instance;
    }

    public PermissonUtil setOnPermissionResultListener(OnPermissionResultListener listener) {
        onPermissionResultListener = listener;
        return this;
    }

    public PermissonUtil setShowSettingsWhenDenied(boolean isShow) {
        showSettingsWhenDenied = isShow;
        return this;
    }

    public void checkPermissions(Activity context, String[] permissions, @NonNull OnPermissionResultListener listener) {
        onPermissionResultListener = listener;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            //6.0才用动态权限
            onPermissionResultListener.onPermissionsPassed();
            return;
        }

        //创建一个mPermissionList，逐个判断哪些权限未授予，未授予的权限存储到mPerrrmissionList中
        List<String> mPermissionList = new ArrayList<>();
        //逐个判断你要的权限是否已经通过
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(context, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);//添加还未授予的权限
            }
        }
        //申请权限
        if (mPermissionList.size() > 0) {//有权限没有通过，需要申请
            ActivityCompat.requestPermissions(context, permissions, REQUEST_CODE_PERMISSIONS);
        } else {
            //说明权限都已经通过，可以做你想做的事情去
            listener.onPermissionsPassed();
            return;
        }
    }

    // 参数： permissions  是我们请求的权限名称数组
    // 参数： grantResults 是我们在弹出页面后是否允许权限的标识数组，数组的长度对应的是权限名称数组的长度，数组的数据0表示允许权限，-1表示我们点击了禁止权限
    public void onRequestPermissionsResult(Activity context, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        boolean hasPermissionDenied = false;
        //有权限没有通过
        if (REQUEST_CODE_PERMISSIONS == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDenied = true;
                }
            }
            //如果有权限没有被允许
            if (hasPermissionDenied) {
                if (showSettingsWhenDenied) {
                    showSystemPermissionsSettingDialog(context);//跳转到系统设置权限页面，或者直接关闭页面，不让他继续访问
                } else {
                    onPermissionResultListener.onPermissionsDenied();
                }
            } else {
                //全部权限通过，可以进行下一步操作。。。
                onPermissionResultListener.onPermissionsPassed();
            }
        }
    }

    /**
     * 不再提示权限时的展示对话框
     */


    private void showSystemPermissionsSettingDialog(final Activity context) {
        if (mPermissionDialog == null) {
            mPermissionDialog = new AlertDialog.Builder(context).setMessage("已禁用权限，请手动授予").setPositiveButton("设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    cancelPermissionDialog();
                    Uri packageURI = Uri.parse("package:" + context.getPackageName());
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                    context.startActivity(intent);
                    context.finish();
                }
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    cancelPermissionDialog();
                    context.finish();
                }
            }).create();
        }
        mPermissionDialog.show();
        //放在show()之后，不然有些属性是没有效果的，比如height和width
        //以下代码设置解决弹窗不居中问题，一侧有边距，一侧没有
        Window dialogWindow = mPermissionDialog.getWindow();
        WindowManager m = context.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        // 设置宽度
        p.width = (int) (d.getWidth() * 0.95); // 宽度设置为屏幕的0.95
        p.gravity = Gravity.CENTER;//设置位置
        //p.alpha = 0.8f;//设置透明度
        dialogWindow.setAttributes(p);

    }

    private void cancelPermissionDialog() {
        if (mPermissionDialog != null) {
            mPermissionDialog.cancel();
            mPermissionDialog = null;
        }
    }


    public interface OnPermissionResultListener {
        void onPermissionsPassed();
        void onPermissionsDenied();
    }
}
